package wsi.input.feedback;

import java.util.Arrays;
import java.util.Comparator;
import java.util.HashSet;
import java.util.Set;

import org.rygh.semantic.func.RdfFunctionalityController;
import org.rygh.semantic.gui.swing.input.Input;
import org.rygh.semantic.model.ex.PredicatePath;
import org.rygh.semantic.model.rdf.Predicate;

import wsi.match.MatchPair;
import wsi.match.SubtreeMatch;
import wsi.subgraph.tree.EntityBranch;
import wsi.subgraph.tree.EntityLeaf;
import wsi.subgraph.tree.EntityTree;

public class FeedbackTuple implements Comparable<FeedbackTuple> {

	private final Set<Predicate> predicateSet = new HashSet<>();
	private final Input input;

	private SubtreeMatch subtreeMatch;
	private EntityTree entityTree;

	public FeedbackTuple(Input input) {
		this.input = input;

	}

	@Override
	public int compareTo(FeedbackTuple o) {
		return o.predicateSet.size() - predicateSet.size();
	}

	public Input getInput() {
		return input;
	}

	public Set<Predicate> getPredicateSet() {
		return predicateSet;
	}

	public Predicate[] getSortedPredicates() {
		Predicate[] predicates = predicateSet
				.toArray(new Predicate[predicateSet.size()]);

		Arrays.sort(predicates, new Comparator<Predicate>() {

			@Override
			public int compare(Predicate o1, Predicate o2) {
				RdfFunctionalityController ctrl = RdfFunctionalityController
						.shared();

				return (int) (ctrl.getInverseFunctionality(o2) * 100 - ctrl
						.getInverseFunctionality(o1) * 100);
			}
		});

		return predicates;
	}

	public void load() {
		EntityLeaf inputNode = entityTree.getConcreteRoot();

		for (MatchPair pair : subtreeMatch.getMatchPairs()) {
			EntityLeaf node = pair.getEntityLeaf();
			EntityBranch branch = entityTree.link(inputNode, node);

			PredicatePath ppath = branch.getPredicatePath();
			Predicate pred = ppath.getFirstPredicate();

			// System.out.printf("pred_path %s\n", ppath.getKey());
			// System.out.printf("pred %s\n", pred.toString());

			predicateSet.add(pred);
		}
	}

	public void setEntityTree(EntityTree entityTree) {
		this.entityTree = entityTree;
	}

	public void setSubtreeMatch(SubtreeMatch subtreeMatch) {
		this.subtreeMatch = subtreeMatch;
	}
}
